<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="公告标题">
          <el-input 
            v-model="queryParams.title" 
            placeholder="请输入公告标题" 
            clearable 
          />
        </el-form-item>
        <el-form-item label="公告类型">
          <el-select v-model="queryParams.announcementType" placeholder="请选择公告类型" clearable>
            <el-option label="系统公告" value="0" />
            <el-option label="活动公告" value="1" />
            <el-option label="重要通知" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="0" />
            <el-option label="已发布" value="1" />
            <el-option label="已下线" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="置顶">
          <el-select v-model="queryParams.isTop" placeholder="是否置顶" clearable>
            <el-option label="否" value="0" />
            <el-option label="是" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleAdd">发布公告</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table
      v-loading="loading"
      :data="announcementList"
      border
      style="width: 100%"
    >
      <el-table-column prop="announcementId" label="ID" width="80" align="center" />
      <el-table-column prop="title" label="公告标题" min-width="200" />
      <el-table-column label="公告类型" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getAnnouncementTypeTagType(scope.row.announcementType)">
            {{ getAnnouncementTypeText(scope.row.announcementType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="publisherName" label="发布者" width="100" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="置顶" width="80" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.isTop === '1' ? 'warning' : 'info'">
            {{ scope.row.isTop === '1' ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="viewCount" label="浏览量" width="100" align="center" />
      <el-table-column prop="publishTime" label="发布时间" width="160" />
      <el-table-column label="操作" width="320" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)">查看</el-button>
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            v-if="scope.row.status === '0'" 
            type="success" 
            size="small" 
            @click="handleUpdateStatus(scope.row, '1')"
          >
            发布
          </el-button>
          <el-button 
            v-if="scope.row.status === '1'" 
            type="warning" 
            size="small" 
            @click="handleUpdateStatus(scope.row, '2')"
          >
            下线
          </el-button>
          <el-button 
            v-if="scope.row.isTop === '0'" 
            type="warning" 
            size="small" 
            @click="handleUpdateTop(scope.row, '1')"
          >
            置顶
          </el-button>
          <el-button 
            v-else 
            type="info" 
            size="small" 
            @click="handleUpdateTop(scope.row, '0')"
          >
            取消置顶
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 公告表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告类型" prop="announcementType">
          <el-select v-model="form.announcementType" placeholder="请选择公告类型">
            <el-option label="系统公告" value="0" />
            <el-option label="活动公告" value="1" />
            <el-option label="重要通知" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="8"
            placeholder="请输入公告内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 公告详情对话框 -->
    <el-dialog
      title="公告详情"
      v-model="detailVisible"
      width="700px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="公告ID">{{ detailForm.announcementId }}</el-descriptions-item>
        <el-descriptions-item label="公告标题">{{ detailForm.title }}</el-descriptions-item>
        <el-descriptions-item label="公告类型">
          <el-tag :type="getAnnouncementTypeTagType(detailForm.announcementType)">
            {{ getAnnouncementTypeText(detailForm.announcementType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发布者">{{ detailForm.publisherName }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(detailForm.status)">
            {{ getStatusText(detailForm.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否置顶">
          <el-tag :type="detailForm.isTop === '1' ? 'warning' : 'info'">
            {{ detailForm.isTop === '1' ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="浏览次数">{{ detailForm.viewCount }}</el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ detailForm.publishTime }}</el-descriptions-item>
        <el-descriptions-item label="公告内容">
          <div class="detail-content">{{ detailForm.content }}</div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAnnouncementPage, 
  getAnnouncementDetail, 
  publishAnnouncement, 
  updateAnnouncement,
  deleteAnnouncement,
  updateAnnouncementStatus,
  updateAnnouncementTop
} from '@/api/announcement'
import { handlePageResponse } from '@/utils/pagination'

// 公告列表
const announcementList = ref([])
// 总数据量
const total = ref(0)
// 加载状态
const loading = ref(false)
// 提交加载状态
const submitLoading = ref(false)
// 表单对话框可见状态
const dialogVisible = ref(false)
// 详情对话框可见状态
const detailVisible = ref(false)
// 表单对话框标题
const dialogTitle = ref('发布公告')
// 表单引用
const formRef = ref(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  announcementType: '',
  status: '',
  isTop: ''
})

// 表单数据
const form = reactive({
  announcementId: null,
  title: '',
  content: '',
  announcementType: ''
})

// 详情表单
const detailForm = ref({})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  announcementType: [
    { required: true, message: '请选择公告类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 10, max: 2000, message: '长度在 10 到 2000 个字符', trigger: 'blur' }
  ]
}

// 获取公告类型文本
const getAnnouncementTypeText = (type) => {
  const typeMap = {
    '0': '系统公告',
    '1': '活动公告',
    '2': '重要通知'
  }
  return typeMap[type] || '未知类型'
}

// 获取公告类型标签类型
const getAnnouncementTypeTagType = (type) => {
  const typeMap = {
    '0': 'primary',
    '1': 'success',
    '2': 'danger'
  }
  return typeMap[type] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    '0': '草稿',
    '1': '已发布',
    '2': '已下线'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    '0': 'info',
    '1': 'success',
    '2': 'warning'
  }
  return statusMap[status] || ''
}

// 初始化数据
onMounted(async () => {
  await fetchData()
})

// 获取公告列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getAnnouncementPage(queryParams)
    const { list, total: totalCount } = handlePageResponse(res)
    announcementList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryParams.title = ''
  queryParams.announcementType = ''
  queryParams.status = ''
  queryParams.isTop = ''
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  fetchData()
}

// 处理添加公告
const handleAdd = () => {
  dialogTitle.value = '发布公告'
  resetForm()
  dialogVisible.value = true
}

// 处理编辑公告
const handleEdit = (row) => {
  dialogTitle.value = '编辑公告'
  resetForm()
  Object.assign(form, row)
  dialogVisible.value = true
}

// 处理查看公告详情
const handleView = async (row) => {
  try {
    const res = await getAnnouncementDetail(row.announcementId)
    if (res.code === 200) {
      detailForm.value = res.data
      detailVisible.value = true
    }
  } catch (error) {
    console.error('获取公告详情失败:', error)
    ElMessage.error('获取公告详情失败')
  }
}

// 处理删除公告
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认要删除公告"${row.title}"吗？此操作将永久删除该公告，无法恢复！`,
    '警告',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteAnnouncement(row.announcementId)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      fetchData()
    } catch (error) {
      console.error('删除公告失败:', error)
      ElMessage({
        type: 'error',
        message: '删除失败，请稍后再试'
      })
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

// 处理更新公告状态
const handleUpdateStatus = (row, status) => {
  const statusText = getStatusText(status)
  ElMessageBox.confirm(
    `确认将公告"${row.title}"设为${statusText}状态吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      await updateAnnouncementStatus(row.announcementId, status)
      ElMessage({
        type: 'success',
        message: `状态更新成功!`
      })
      fetchData()
    } catch (error) {
      console.error('更新公告状态失败:', error)
      ElMessage({
        type: 'error',
        message: '状态更新失败'
      })
    }
  })
}

// 处理置顶/取消置顶
const handleUpdateTop = (row, isTop) => {
  const actionText = isTop === '1' ? '置顶' : '取消置顶'
  ElMessageBox.confirm(
    `确认${actionText}公告"${row.title}"吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      await updateAnnouncementTop(row.announcementId, isTop)
      ElMessage({
        type: 'success',
        message: `${actionText}成功!`
      })
      fetchData()
    } catch (error) {
      console.error(`${actionText}失败:`, error)
      ElMessage({
        type: 'error',
        message: `${actionText}失败`
      })
    }
  })
}

// 重置表单
const resetForm = () => {
  form.announcementId = null
  form.title = ''
  form.content = ''
  form.announcementType = ''
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      if (form.announcementId) {
        await updateAnnouncement(form)
        ElMessage({
          type: 'success',
          message: '更新成功!'
        })
      } else {
        await publishAnnouncement(form)
        ElMessage({
          type: 'success',
          message: '发布成功!'
        })
      }
      dialogVisible.value = false
      fetchData()
    } catch (error) {
      console.error('保存公告失败:', error)
      ElMessage({
        type: 'error',
        message: '保存失败，请稍后再试'
      })
    } finally {
      submitLoading.value = false
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.detail-content {
  max-width: 500px;
  line-height: 1.6;
  word-break: break-all;
  white-space: pre-wrap;
}
</style>

